<template>
  <div class="image-collections-container">
    <el-card class="table-card">
      <div class="table-header">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增图片集</el-button>
      </div>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="图片集名称" min-width="120"></el-table-column>
        <el-table-column label="所属分类" width="120">
          <template slot-scope="scope">
            {{ getCategoryName(scope.row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column label="封面图" width="150" align="center">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.coverImage"
              style="width: 100px; height: 60px"
              :src="scope.row.coverImage" 
              :preview-src-list="[scope.row.coverImage]">
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="imageCount" label="图片数量" width="100" align="center"></el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center"></el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170" align="center"></el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="success" icon="el-icon-picture" @click="goToDetail(scope.row)">管理图片</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParams.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm('form')">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="图片集名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入图片集名称"></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择所属分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" placeholder="请输入排序"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          ></el-switch>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="customUpload"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.coverImage" :src="form.coverImage" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" :rows="3" placeholder="请输入图片集描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ImageCollections',
  data() {
    return {
      // 分页参数
      pageParams: {
        current: 1,
        size: 10
      },
      // 表格数据
      tableData: [],
      total: 0,
      loading: false,
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增图片集',
      // 表单数据
      form: {
        id: null,
        name: '',
        categoryId: '',
        description: '',
        coverImage: '',
        sort: 0,
        status: 1
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入图片集名称', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择所属分类', trigger: 'change' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      },
      // 分类选项
      categoryOptions: []
    }
  },
  created() {
    this.fetchCategories();
    this.fetchData();
  },
  methods: {
    // 获取分类列表
    fetchCategories() {
      request({
        url: '/car-vehicle/image/category/page',
        method: 'get',
        params: {
          current: 1,
          size: 100
        }
      }).then(res => {
        if (res.code === 200) {
          this.categoryOptions = res.data.records;
        }
      });
    },
    // 获取图片集列表数据
    fetchData() {
      this.loading = true;
      request({
        url: '/car-vehicle/image/collection/page',
        method: 'get',
        params: {
          current: this.pageParams.current,
          size: this.pageParams.size
        }
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        } else {
          this.$message.error(res.message || '获取图片集列表失败');
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        // 模拟数据，实际项目中应该从后端API获取
        setTimeout(() => {
          this.tableData = [
            {
              id: 1,
              name: '轿车展示图集',
              categoryId: 1,
              description: '各种轿车的展示图片集合',
              coverImage: 'https://via.placeholder.com/300x180?text=轿车展示',
              imageCount: 12,
              sort: 1,
              status: 1,
              createTime: '2023-06-15 10:00:00'
            },
            {
              id: 2,
              name: 'SUV展示图集',
              categoryId: 1,
              description: '各种SUV的展示图片集合',
              coverImage: 'https://via.placeholder.com/300x180?text=SUV展示',
              imageCount: 8,
              sort: 2,
              status: 1,
              createTime: '2023-06-15 11:00:00'
            },
            {
              id: 3,
              name: '奔驰品牌展示',
              categoryId: 2,
              description: '奔驰品牌的展示图片集合',
              coverImage: 'https://via.placeholder.com/300x180?text=奔驰品牌',
              imageCount: 5,
              sort: 3,
              status: 1,
              createTime: '2023-06-15 12:00:00'
            }
          ];
          this.total = this.tableData.length;
          this.loading = false;
        }, 500);
      });
    },
    // 获取分类名称
    getCategoryName(categoryId) {
      const category = this.categoryOptions.find(item => item.id === categoryId);
      return category ? category.name : '未知分类';
    },
    // 处理页码变更
    handleCurrentChange(current) {
      this.pageParams.current = current;
      this.fetchData();
    },
    // 处理每页数量变更
    handleSizeChange(size) {
      this.pageParams.size = size;
      this.pageParams.current = 1;
      this.fetchData();
    },
    // 处理新增
    handleAdd() {
      this.dialogTitle = '新增图片集';
      this.form = {
        id: null,
        name: '',
        categoryId: '',
        description: '',
        coverImage: '',
        sort: 0,
        status: 1
      };
      this.dialogVisible = true;
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑图片集';
      this.form = { ...row };
      this.dialogVisible = true;
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm('确认删除该图片集?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: `/car-vehicle/image/collection/${row.id}`,
          method: 'delete'
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.fetchData();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        }).catch(() => {
          // 模拟删除操作
          this.tableData = this.tableData.filter(item => item.id !== row.id);
          this.total = this.tableData.length;
          this.$message.success('删除成功');
        });
      }).catch(() => {});
    },
    // 处理状态变更
    handleStatusChange(row) {
      request({
        url: '/car-vehicle/image/collection/status',
        method: 'put',
        params: {
          id: row.id,
          status: row.status
        }
      }).then(res => {
        if (res.code === 200) {
          this.$message.success('状态修改成功');
        } else {
          row.status = row.status === 1 ? 0 : 1; // 恢复原状态
          this.$message.error(res.message || '状态修改失败');
        }
      }).catch(() => {
        // 模拟状态变更操作
        this.$message.success('状态修改成功');
      });
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const method = this.form.id ? 'put' : 'post';
          request({
            url: '/car-vehicle/image/collection',
            method,
            data: this.form
          }).then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.form.id ? '更新' : '添加'}成功`);
              this.dialogVisible = false;
              this.fetchData();
            } else {
              this.$message.error(res.message || `${this.form.id ? '更新' : '添加'}失败`);
            }
          }).catch(() => {
            // 模拟提交操作
            if (this.form.id) {
              // 编辑
              const index = this.tableData.findIndex(item => item.id === this.form.id);
              if (index !== -1) {
                this.tableData[index] = { 
                  ...this.form,
                  imageCount: this.tableData[index].imageCount
                };
              }
            } else {
              // 新增
              const newId = Math.max(...this.tableData.map(item => item.id), 0) + 1;
              this.tableData.push({
                ...this.form,
                id: newId,
                imageCount: 0,
                createTime: new Date().toLocaleString()
              });
              this.total = this.tableData.length;
            }
            
            this.$message.success(`${this.form.id ? '更新' : '添加'}成功`);
            this.dialogVisible = false;
          });
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 图片上传前处理
    beforeImageUpload(file) {
      const isImage = file.type.indexOf('image/') === 0;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    // 自定义上传方法
    customUpload(event) {
      const file = event.file;
      const formData = new FormData();
      formData.append('file', file);

      request({
        url: '/car-integration/files/upload',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.code === 200) {
          this.handleCoverSuccess(res, file);
        } else {
          this.$message.error('上传失败：' + res.message);
        }
      }).catch(() => {
        this.$message.error('上传失败');
      });
    },
    // 封面图上传成功处理
    handleCoverSuccess(res, file) {
      if (res.code === 200) {
        this.form.coverImage = res.data.url;
        this.$message.success('上传成功');
      } else {
        this.$message.error('上传失败：' + res.message);
      }
    },
    // 跳转到图片集详情
    goToDetail(row) {
      this.$router.push({
        name: 'ImageCollectionDetail',
        params: { collectionId: row.id },
        query: { collectionName: row.name }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.image-collections-container {
  padding: 20px;
  
  .table-card {
    .table-header {
      margin-bottom: 20px;
      display: flex;
      justify-content: flex-start;
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 100px;
    
    &:hover {
      border-color: #409EFF;
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    
    .avatar {
      width: 178px;
      height: 100px;
      display: block;
      object-fit: cover;
    }
  }
}
</style> 